package com.hou;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(value = "service-order")
@EnableCaching
public class ServiceUserApplication {

    //RestTemplateBuilder已经默认注入
    @Autowired
    private RestTemplateBuilder restTemplateBuilder;
    //将RestTemplate加入容器中
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return restTemplateBuilder.build();
    }

    @Bean
    public LoadingCache<String, Object> loadingCache(){
        LoadingCache<String, Object> build = CacheBuilder.newBuilder()
                //设置回收策略,有两种
                .expireAfterWrite(1, TimeUnit.MINUTES) //设置写入一分钟之后回收
                //.expireAfterAccess(1,TimeUnit.MINUTES)  //设置如果1分钟之内没有读取就回收
                .maximumSize(100)  //设置最大值,超出容量后会尝试清楚最近不常使用的值
                .build(new CacheLoader<String, Object>() {
                    @Override
                    public Object load(String s) throws Exception {
                        return null;
                    }
                });
        build.put("name","侯征");
        build.put("age",25);
        return build;
    }

    public static void main(String[] args) {

        SpringApplication.run(ServiceUserApplication.class, args);
    }
}
